import { _decorator, Asset, Node, resources, SpriteFrame, Sprite, AudioClip, Prefab } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 负责加载各种游戏资源（如背景图、音效、预制体等）。
 */
@ccclass('ResourceManager')
export class ResourceManager {

    // 加载指定路径的资源并返回加载结果
    static loadResource<T extends Asset>(resourcePath: string, type: new () => T, callback: (err: Error | null, resource: T | null) => void): void {
        resources.load(resourcePath, type, (err, resource) => {
            callback(err, resource);
        });
    }

    // 加载背景图片资源
    static loadBackground(node: Node, resourcePath: string): void {
        this.loadResource(resourcePath, SpriteFrame, (err, spriteFrame) => {
            if (err) {
                console.error('加载背景图像失败:', err);
                return;
            }
            const sprite = node.getComponent(Sprite);
            if (sprite) {
                sprite.spriteFrame = spriteFrame;  // 设置背景图片
            }
        });
    }

    // 加载音效资源
    static loadAudio(resourcePath: string, callback: (err: Error | null, audioClip: AudioClip | null) => void): void {
        this.loadResource(resourcePath, AudioClip, callback);
    }

    // 加载预制体资源
    static loadPrefab(resourcePath: string, callback: (err: Error | null, prefab: Prefab | null) => void): void {
        this.loadResource(resourcePath, Prefab, callback);
    }

    // 使用 Promise 来加载资源，便于 async/await 调用
    static loadResourceAsync<T extends Asset>(resourcePath: string, type: new () => T): Promise<T> {
        return new Promise((resolve, reject) => {
            this.loadResource(resourcePath, type, (err, resource) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(resource!);
                }
            });
        });
    }

    // 使用 async/await 加载背景
    static async loadBackgroundAsync(node: Node, resourcePath: string): Promise<void> {
        try {
            const spriteFrame = await this.loadResourceAsync(resourcePath, SpriteFrame);
            const sprite = node.getComponent(Sprite);
            if (sprite) {
                sprite.spriteFrame = spriteFrame;  // 设置背景图片
            }
        } catch (err) {
            console.error('加载背景图像失败:', err);
        }
    }
}


